
#include "librtspclient.h"

#include <thread>

#include "testRTSPClient.h"

char eventLoopWatchVariable = 0;
RTSPCLI_API int MyRTSP_Init(RTSP_Handle **handle) {
  TaskScheduler *scheduler = BasicTaskScheduler::createNew();
  UsageEnvironment *env = BasicUsageEnvironment::createNew(*scheduler);
  *handle = env;
  return 0;
}

RTSPCLI_API int MyRTSP_Deinit(RTSP_Handle *handle) {
  if (!handle) {
    return -1;
  }
  eventLoopWatchVariable = 1;
  handle = nullptr;
  return 0;
}

RTSPCLI_API int MyRTSP_OpenStream(RTSP_Handle *handle, const char *_url,
                                  EASY_RTP_CONNECT_TYPE _connType,
                                  int _reconn) {
  if (!handle) {
    return -1;
  }
  eventLoopWatchVariable = 0;
  UsageEnvironment *env = (UsageEnvironment *)handle;
  SET_REQUEST_STREAMING_OVER_TYPE(_connType);

  openURL(*env, "livestring", _url);

  printf("%s %d\n", __FUNCTION__, __LINE__);

  // std::thread([env] {
  //   env->taskScheduler().doEventLoop(&eventLoopWatchVariable);
  //   printf("%s %d\n", __FUNCTION__, __LINE__);
  // }).detach();
  // env->taskScheduler().doEventLoop(&eventLoopWatchVariable);
  return 0;
}

RTSPCLI_API int MyRTSP_SetCallback(RTSP_Handle *handle,
                                   RTSPSourceCallBack _callback,
                                   void *userptr) {
  if (!handle) {
    return -1;
  }
  SetFrameCallback(_callback, userptr);
  return 0;
}

RTSPCLI_API int MyRTSP_CloseStream(RTSP_Handle *handle) {
  if (!handle) {
    return -1;
  }
  eventLoopWatchVariable = 1;
  return 0;
}

RTSPCLI_API int MyRTSP_Run(RTSP_Handle *handle) {
  if (!handle) {
    return -1;
  }
  eventLoopWatchVariable = 0;
  UsageEnvironment *env = (UsageEnvironment *)handle;
  env->taskScheduler().doEventLoop(&eventLoopWatchVariable);
  return 0;
}
